import React from 'react'
import { Button, message, Input, Modal, Radio, Select } from 'antd'
import { BaseListPage, IBaseListPageProps, IBaseListPageState, uaaApp, validators } from '../../../lib'
import { columnRenders } from '../../../lib/utils/columnRenders'
import { UdModal, UdModalForm } from '../../../lib/ui/UdModal'
import { http } from '../../../lib/core/http'
import TextArea from 'antd/lib/input/TextArea'
import SourceTree from '../component/SourceTree'
import apis from "@/apis/RolePermissions"

const confirm = Modal.confirm
const Option = Select.Option

const AddBtnAuth = 'user_auth_dealer_add'
const UpdateBtnAuth = 'user_auth_dealer_add'
const DeleteBtnAuth = 'user_auth_dealer_delete'
const AddAuthBtnAuth = 'user_auth_dealer_addAgentRoleAuth'
class RolePermissionsList extends BaseListPage<IRolePermissionsListProps, IRolePermissionsListState> {

  protected saveParamsWithUrl: boolean = true
/* 已选资源的父级id和已选id集合 */
  private allSourceCheckKeys: string[] = []

  constructor(props: IRolePermissionsListProps) {
    super(props)

    this.state = {
      title: '经销商角色列表',
      queryApi: apis.DealerRoleList,
      method: 'GET',
      conditions: [
        { id: 'agentCode', label: '经销商',render: <Input placeholder='请输入经销商名称或编码' />},
        { id: 'roleName', label: '角色名' },
      ],
      rowKey: 'id',
      columns: [
        ['经销商名称', 'agentName'],
        ['经销商编码', 'agentCode'],
        ['角色名', 'roleName'],
        ['备注', 'remarkOne'],
        ['创建时间', 'createTime' ],
        ['最近修改时间', 'updateTime' ],
        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '140px',
          allowCustomize: false,
          render: columnRenders.operate([
            {
              title: '编辑', auth: UpdateBtnAuth, action: (text: any, row: any) => this.edit(row)
            },
            {
              title: '资源配置', auth: AddAuthBtnAuth, action: (text: any, record: any) => this.setSource(record)
            },
            {
              title: '删除', auth: DeleteBtnAuth, action: (text: any, record: any) => {
                confirm({
                  title: '确定要删除该角色吗？',
                  onOk: () => {
                    return this.deleteRole(record)
                  }
                })
              }
            },
          ])
        }
      ],
      leftBtns: [
        uaaApp.canUse(AddBtnAuth)&&<Button type="primary" onClick={this.addRole}>新增角色</Button>
      ],
      tableProps: {
        rowSelection: null,
      },
      dealerList: [],
    }
  }

  public componentWillMount() {
    super.componentWillMount()
    this.getDealerList()
  }

  private getDealerList = () => {
    http.get(apis.DealerSelectList).then(res=>{
      const dealerList = res.data?.map(({agentCode,agentName})=>({value:agentCode,title:agentName})) || []
      this.setState({
        dealerList,
      })
    })
  }

  private setSource = (row) => {
    UdModal.open({
      title: '资源配置',
      content: <UdModalForm items={[
        { id: 'authId', label: '资源权限', render: <SourceTree roleId={row.id} url={apis.AuthDealerTreeList} onCheck={this.sourceTreeCheckHandle} /> },
      ]} />,
      onOk: (values) => {
        values.roleId = row.id
        values.authId = this.allSourceCheckKeys
        return http.post(apis.AddDealerRoleAuth, values).then(res=>{
          message.success('配置成功')
        })
      }
    })
  }

  private addRole = () => {
    const { dealerList } = this.state
    UdModal.open({
      title: '新增角色',
      content: <UdModalForm items={[
        { id: 'agentCode', label: '经销商', rules: [validators.required], render: ()=>(
          <Select mode='multiple' placeholder="请选择经销商">
            {dealerList.map(({value,title})=>(<Option value={value}>{title}</Option>))}
          </Select>
        ) },
        { id: 'roleName', label: '角色名', rules: [validators.required, validators.max(20), validators.noSymbol] },
        { id: 'remarkOne', label: '备注', rules: [validators.max(40), validators.noSpecialSymbol], render: <TextArea /> },
      ]} />,
      onOk: (values) => {
        return http.post(apis.AddDealerRole, values).then(res=>{
          message.success('新增成功')
          this.query()
        })
      }
    })
  }

  private edit = (row) => {
    UdModal.open({
      title: '编辑',
      content: <UdModalForm items={[
        { id: 'agentName', label: '经销商', render: ()=>(<div>{row['agentName']}</div>)},
        { id: 'roleName', label: '角色名', rules: [validators.required, validators.max(20), validators.noSymbol]},
        { id: 'remarkOne', label: '备注', rules: [validators.max(40), validators.noSpecialSymbol], render: <TextArea /> },
      ]} values={row} />,
      onOk: (values) => {
        values.id = row.id
        return http.put(apis.UpdateDealerRole, values).then(res=>{
          message.success('编辑成功')
          this.query()
        })
      }
    })
  }

  private deleteRole = (row) => {
    return http.delete(apis.DeleteDealerRole, {params:{id: row.id}}).then(res=>{
      message.success('删除成功')
      this.query()
    })
  }

  private sourceTreeCheckHandle = (keys) => {
    this.allSourceCheckKeys = keys
  }

}

interface IRolePermissionsListProps extends IBaseListPageProps {

}

interface IRolePermissionsListState extends IBaseListPageState {
  dealerList: [{value:any,title:string}?]
}

export default RolePermissionsList


function RadioCm(props) {
  return (
    <Radio.Group onChange={props.onChange} value={props.value}>
      <Radio value={0}>内部员工系统</Radio>
      <Radio value={1}>经销商系统</Radio>
    </Radio.Group>
  )
}
